import { login, logout, LogoutParams, getRoleMenu } from '@/service/user';
import { LoginData, UserInfo } from '@/service/user';
import router from '@/router';

const InitUserInfo: UserInfo = {
  id: 0,
  username: '',
  realName: '',
  avatar: '',
  roles: [],
  permissions: [],
};

// 定义的state初始值
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: InitUserInfo,
  permissions: [],
  roles: [],
  fullUserData: null, // 存储完整的用户数据
  roleMenu: [], // 存储角色菜单数据
};

const mutations = {
  SET_TOKEN(state, token: string) {
    state.token = token;
    localStorage.setItem('token', token);
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions;
  },
  SET_ROLES(state, roles) {
    state.roles = roles;
  },
  SET_FULL_USER_DATA(state, data) {
    state.fullUserData = data;
    // 可以选择把完整数据也存入localStorage
    localStorage.setItem('userData', JSON.stringify(data));
  },
  SET_ROLE_MENU(state, menu) {
    state.roleMenu = menu;
    // 可以选择将菜单数据保存到localStorage
    localStorage.setItem('roleMenu', JSON.stringify(menu));
  },
  CLEAR_USER(state) {
    state.token = '';
    state.userInfo = InitUserInfo;
    state.permissions = [];
    state.roles = [];
    state.fullUserData = null;
    state.roleMenu = [];
    localStorage.removeItem('token');
    localStorage.removeItem('userData');
    localStorage.removeItem('roleMenu');
  },
};

const getters = {
  token: (state) => state.token,
  userInfo: (state) => state.userInfo,
  roles: (state) => state.roles,
  permissions: (state) => state.permissions,
  fullUserData: (state) => state.fullUserData,
  roleMenu: (state) => state.roleMenu,
  // 便捷访问常用字段
  userId: (state) => state.userInfo?.id || 0,
  userName: (state) => state.userInfo?.username || '',
  realName: (state) => state.userInfo?.realName || '',
  avatar: (state) => state.userInfo?.avatar || '',
};

const actions = {
  // 登录
  async login({ commit, dispatch }, loginData: LoginData) {
    try {
      const { data } = await login(loginData);
      
      // 保存token
      if (data.token) {
        commit('SET_TOKEN', data.token);
      }
      
      // 保存权限信息
      if (data.permissions) {
        commit('SET_PERMISSIONS', data.permissions);
      }
      
      // 保存角色信息
      if (data.roles) {
        commit('SET_ROLES', data.roles);
      }
      
      // 保存用户基本信息
      if (data.user) {
        const userInfo = {
          id: data.user.userId || 0,
          username: data.user.username || '',
          realName: data.user.username || '', // 可能需要调整字段名
          avatar: data.user.avatar || 'default.jpg',
        };
        commit('SET_USERINFO', userInfo);

        // 登录成功后获取菜单
        try {
          await dispatch('getRoleMenu');
        } catch (menuError) {
          console.error('获取角色菜单失败:', menuError);
        }
      }
      
      // 保存完整数据
      commit('SET_FULL_USER_DATA', data);
      
      return Promise.resolve(data);
    } catch (error) {
      return Promise.reject(error);
    }
  },

  // 获取角色菜单 - 现在不需要传递参数
  async getRoleMenu({ commit, dispatch }) {
    try {
      const { data } = await getRoleMenu();
      if (data) {
        commit('SET_ROLE_MENU', data);
        
        // 调用权限模块的initDynamicRoutes方法，初始化动态路由
        await dispatch('permission/initDynamicRoutes', data, { root: true });
        
        // 重载当前页面，确保新路由生效
        if (window.location.pathname !== '/login') {
          window.location.reload();
        }
      }
      return Promise.resolve(data);
    } catch (error) {
      console.error('获取角色菜单失败:', error);
      return Promise.reject(error);
    }
  },
  
  // 登出
  async logout({ commit, state }) {
    try {
      // 从state中获取userId
      const userId = state.userInfo?.id || state.fullUserData?.user?.userId || 0;
      
      // 创建登出参数
      const logoutParams: LogoutParams = { userId };
      
      // 调用登出接口并传递userId
      await logout(logoutParams);
      
      commit('CLEAR_USER');
      // 重定向到登录页
      router.push('/login');
      return Promise.resolve();
    } catch (error) {
      return Promise.reject(error);
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
